package com.example.musicplayer.viewTools;

import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;

//View组件的消失和出现动画
public class ViewAlphaAnimation {
    private float mMinAlpha;
    private float mMaxAlpha;
    private int mDuration;
    private AlphaAnimation mAppear;
    private AlphaAnimation mDisappear;
    //在进行消失动画时，防止动画被打断导致组件没有达到消失效果，
    //因为在消失动画结束才设置组件visibility=GONE
    private boolean mDisappearFlag;

    public ViewAlphaAnimation() {
        this(0, 1, 300);
    }

    public ViewAlphaAnimation(float minAlpha, float maxAlpha, int duration) {
        mMinAlpha = minAlpha;
        mMaxAlpha = maxAlpha;
        mDuration = duration;
        mDisappearFlag = false;
        initAnimation();
    }

    //创建动画对象
    private void initAnimation() {
        mAppear = new AlphaAnimation(mMinAlpha, mMaxAlpha);
        mAppear.setDuration(mDuration);
        mDisappear = new AlphaAnimation(mMaxAlpha, mMinAlpha);
        mDisappear.setDuration(mDuration);
    }

    public void setMinAlpha(float minAlpha) {
        if (minAlpha >= 0 && minAlpha <= 1) {
            mMinAlpha = minAlpha;
            initAnimation();
        }
    }

    public void setMaxAlpha(float maxAlpha) {
        if (maxAlpha >= 0 && maxAlpha <= 1)
            mMaxAlpha = maxAlpha;
        initAnimation();
    }

    public void setDuration(int duration) {
        if (duration >= 0) {
            mDuration = duration;
            mAppear.setDuration(mDuration);
            mDisappear.setDuration(mDuration);
        }
    }

    //出现动画
    public void appear(View view) {
        if (view != null && view.getVisibility() == View.GONE) {
            if (mAppear == null)
                initAnimation();
            view.startAnimation(mAppear);
            view.setVisibility(View.VISIBLE);
        }
    }

    //消失动画
    public void disappear(final View view) {
        if (view != null && view.getVisibility() == View.VISIBLE) {
            if (mDisappear == null)
                initAnimation();
            //判断是否正在执行消失动画
            if (mDisappearFlag)
                return;
            mDisappearFlag = true;
            view.startAnimation(mDisappear);
            mDisappear.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view.setVisibility(View.GONE);
                    //动画完毕，把flag置为false表示动画结束
                    mDisappearFlag = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
    }
}